package com.atguigu.consumer;

import com.alibaba.fastjson.JSON;
import com.atguigu.client.PaymentFeignClient;
import com.atguigu.constant.MqConst;
import com.atguigu.entity.OrderInfo;
import com.atguigu.entity.PaymentInfo;
import com.atguigu.enums.OrderStatus;
import com.atguigu.enums.PaymentStatus;
import com.atguigu.enums.ProcessStatus;
import com.atguigu.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class OrderConsumer {
    @Autowired
    private OrderInfoService orderService;
    @Autowired
    private PaymentFeignClient paymentFeignClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 1.取消订单的监视器
     * 因为我们设置了CancelOrderQueueConfig类 所以这里可以简单写
     */
    @RabbitListener(queues = MqConst.CANCEL_ORDER_QUEUE)
    public void cancelOrder(Long orderId, Message message, Channel channel) throws IOException {
        if(orderId!=null){
            //根据订单id查询订单信息
            OrderInfo orderInfo = orderService.getById(orderId);
            if(orderInfo!=null&&orderInfo.getOrderStatus().equals(OrderStatus.UNPAID.name())){
                //修改订单状态为已关闭
                orderService.updateOrderStatus(orderInfo, ProcessStatus.CLOSED);
                //关闭支付订单信息
                PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                if(paymentInfo!=null&&paymentInfo.getPaymentStatus().equals(PaymentStatus.UNPAID.name())){
                    //发送一条消息给支付系统
                    rabbitTemplate.convertAndSend(MqConst.CLOSE_PAYMENT_EXCHANGE,MqConst.CLOSE_PAYMENT_ROUTE_KEY,orderId);
                    boolean flag = paymentFeignClient.queryAlipayTrade(orderId);
                    if(flag){
                        //关闭支付宝交易记录
                        paymentFeignClient.closeAlipayTrade(orderId);
                    }
                }
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //2.支付成功之后修改订单状态
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.PAY_ORDER_QUEUE,durable = "false"),
            exchange = @Exchange(value = MqConst.PAY_ORDER_EXCHANGE,durable = "false"),
            key = {MqConst.PAY_ORDER_ROUTE_KEY}))
    public void updateOrderAfterPaySuccess(Long orderId,Message message, Channel channel) throws IOException {
        if(orderId!=null){
            //根据订单id查询订单信息
            OrderInfo orderInfo = orderService.getOrderInfo(orderId);
            if(orderInfo!=null&&orderInfo.getOrderStatus().equals(ProcessStatus.UNPAID.name())){
                //修改订单状态为已支付
                orderService.updateOrderStatus(orderInfo, ProcessStatus.PAID);
                //通知仓库系统去减库存
                orderService.sendMsgToWareHouse(orderInfo);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
    //3.仓库系统减库存成功之后的消费代码
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.SUCCESS_DECREASE_STOCK_QUEUE,durable = "false"),
            exchange = @Exchange(value = MqConst.SUCCESS_DECREASE_STOCK_EXCHANGE,durable = "false"),
            key = {MqConst.SUCCESS_DECREASE_STOCK_ROUTE_KEY}))
    public void updateOrderStatus(String msgJson,Message message, Channel channel) throws IOException {
        if(StringUtils.isNotEmpty(msgJson)){
            //获取从仓库那边传递过来的信息
            Map<String, String> map = JSON.parseObject(msgJson,Map.class);
            String orderId = map.get("orderId");
            String status = map.get("status");
            OrderInfo orderInfo=orderService.getOrderInfo(Long.parseLong(orderId));
            //如果仓库减库存成功 这边就应该把状态改为已发货
            if("DEDUCTED".equals(status)){
                orderService.updateOrderStatus(orderInfo,ProcessStatus.WAITING_DELEVER);
            }else{
                //减库存失败 超卖
                orderService.updateOrderStatus(orderInfo,ProcessStatus.STOCK_EXCEPTION);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
